<template>
  <div class="user-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryForm" class="search-form">
      <el-form-item label="用户名">
        <el-input v-model="queryForm.username" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="queryForm.phone" placeholder="请输入手机号" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button type="success" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 用户表格 -->
    <div class="table-container">
      <el-table :data="userList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column prop="userName" label="用户名" width="120" />
        <el-table-column prop="loginName" label="登录名" width="120" />
        <el-table-column prop="mobile" label="手机号" width="150" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column label="操作" width="200" >
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      />
    </div>
  </div>

  <!-- 新增/编辑对话框 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%" @close="resetForm">
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="登录名" prop="loginName">
        <el-input v-model="form.loginName" placeholder="请输入登录名" />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="0"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 用户详情对话框 -->
  <el-dialog title="用户详情" v-model="detailVisible" width="40%">
    <div v-if="currentUser">
      <p><strong>用户ID:</strong> {{ currentUser.id }}</p>
      <p><strong>用户名:</strong> {{ currentUser.userName }}</p>
      <p><strong>登录名:</strong> {{ currentUser.loginName }}</p>
      <p><strong>手机号:</strong> {{ currentUser.mobile }}</p>
      <p><strong>邮箱:</strong> {{ currentUser.email }}</p>
      <p><strong>性别:</strong> {{ currentUser.sex === 1 ? '男' : '女' }}</p>
      <p><strong>用户类型:</strong> {{ currentUser.type === 1 ? '普通用户' : '其他' }}</p>
    </div>
    <div v-else>
      加载中...
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailVisible = false">关 闭</el-button>
      </span>
    </template>
  </el-dialog>
  </div>
</template>

<script>
import { getUserList, addUser, updateUser, deleteUser } from '@/api/userApi'

export default {
  name: 'UserManagementComponent',
  data() {
    return {
      // 查询表单
      queryForm: {
        username: '',
        phone: ''
      },
      // 用户列表数据
      userList: [],
      // 分页数据
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 表单数据
      form: {
        id: '',
        loginName: '',
        username: '',
        mobile: '',
        status: 1
      },
      // 对话框状态
      dialogVisible: false,
      dialogTitle: '',
      detailVisible: false,
      currentUser: null,
      // 加载状态
      loading: false,
      // 表单验证规则
      rules: {
        loginName: [
          { required: true, message: '请输入登录名', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 查询用户
    handleQuery() {
      this.pagination.current = 1
      this.fetchUserList()
    },
    // 获取用户列表
    async fetchUserList() {
      this.loading = true
      try {
        const params = {
          ...this.queryForm,
          current: this.pagination.current,
          size: this.pagination.size
        }
        const res = await getUserList(params)
        if (res.data) {
          this.userList = res.data
          this.pagination.total = res.total
        } else {
          this.userList = []
        }
      } catch (error) {
        this.$message.error('获取用户列表失败')
        console.error('获取用户列表错误:', error)
        this.userList = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },
    // 查看用户详情
    handleView(row) {
      console.log('查看按钮被点击', row)
      this.currentUser = row
      this.detailVisible = true
      console.log('detailVisible设置为:', this.detailVisible)
    },
    // 新增用户
    handleAdd() {
      this.dialogTitle = '新增用户'
      this.form = {
        id: '',
        loginName: '',
        username: '',
        mobile: '',
        status: 1
      }
      this.dialogVisible = true
    },
    // 编辑用户
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.form = {
        id: row.id,
        loginName: row.loginName,
        username: row.userName,
        mobile: row.mobile,
        status: row.status || 1
      }
      this.dialogVisible = true
    },
    // 删除用户
    async handleDelete(row) {
      try {
        await this.$confirm(`确定删除用户《${row.userName}》吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.loading = true
        await deleteUser(row.id)
        this.$message.success('删除成功')
        this.fetchUserList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      } finally {
        this.loading = false
      }
    },
    // 提交表单
    async submitForm() {
      try {
        if (!this.$refs.form) return
        const valid = await this.$refs.form.validate()
        if (!valid) return
        this.loading = true
        if (this.form.id) {
          // 更新用户
          await updateUser({
            id: this.form.id,
            loginName: this.form.loginName,
            username: this.form.username,
            mobile: this.form.mobile
          })
          this.$message.success('更新成功')
        } else {
          // 新增用户
          await addUser({
            loginName: this.form.loginName,
            username: this.form.username,
            mobile: this.form.mobile
          })
          this.$message.success('新增成功')
        }
        this.dialogVisible = false
        this.fetchUserList()
      } catch (error) {
        this.$message.error('操作失败，请重试')
        console.error('用户操作失败:', error)
      } finally {
        this.loading = false
      }
    },
    // 重置表单
    resetForm() {
      this.form = {
        id: '',
        loginName: '',
        username: '',
        mobile: '',
        status: 1
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    // 处理分页大小改变
    handleSizeChange(size) {
      this.pagination.size = size
      this.fetchUserList()
    },
    // 处理分页页码改变
    handleCurrentChange(current) {
      this.pagination.current = current
      this.fetchUserList()
    }
  },
  // 创建完毕
  mounted() {
    this.fetchUserList()
  }
}
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.table-container {
  margin: 0 !important;
}

/* 彻底解决el-table样式被全局样式覆盖的问题 */
.table-container :deep(.el-table) {
  margin: 0 !important;
  width: 100% !important;
}

.table-container :deep(.el-table__header-wrapper) {
  margin: 0 !important;
}

.table-container :deep(.el-table__header) {
  margin: 0 !important;
  width: 100% !important;
  table-layout: fixed !important;
  border-collapse: separate !important;
}

.table-container :deep(.el-table__body-wrapper) {
  margin: 0 !important;
}

.table-container :deep(.el-table__body) {
  margin: 0 !important;
  width: 100% !important;
  table-layout: fixed !important;
  border-collapse: separate !important;
}

.table-container :deep(table) {
  margin: 0 !important;
  border-collapse: separate !important;
  table-layout: fixed !important;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.dialog-footer {
  text-align: right;
}
</style>